package com.wechat.api.rpc;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.wechat.api.util.TokenUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.wechat.api.to.ReturnObjectTO;
import com.wechat.api.util.HttpClientUtil;
import com.wechat.api.util.JsonUtil;

/**
 * 消息接收/发送
 */
@RestController
@RequestMapping("/msg")
public class MessageRPC {
	
	private Logger _log = LogManager.getLogger(MessageRPC.class);
	
	private static final String SEND_TEMPLATE_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send";
	private static final String GET_ALL_PRIVATE_TEMPLATE_URL = "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template";
	private static final String OPEN_ID = "oVwSn1amo5IvNLbw3OGde1776UhM";
	private static final String TEMPLATE_ID = "f_dRpw5qI1yBpJZ4slBUWU34CURMPcEznjuRCC5N1yA";
	


	@RequestMapping("alltemplate")
	public ReturnObjectTO getAllTempalte(){
		ReturnObjectTO result = ReturnObjectTO.success();
		try {
			String token = TokenUtil.getAccessToken();
			String doGet = HttpClientUtil.doGet(GET_ALL_PRIVATE_TEMPLATE_URL+"?access_token="+token);
			_log.info(doGet);
			result.put("template", doGet);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	@RequestMapping("sendmsg")
	public ReturnObjectTO sendTemplateMsg(){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH：mm：ss");
		ReturnObjectTO result = ReturnObjectTO.success();
		try {
			String token = TokenUtil.getAccessToken();
			//TODO 推送模板消息
			Map<String, Object> sendParams = new HashMap<String, Object>();
			sendParams.put("touser", OPEN_ID);
			sendParams.put("template_id", TEMPLATE_ID);
			Map<String, Object> dataParams = new HashMap<String, Object>();
			dataParams.put("mercName", returnMap("北京面包小店", "#6da0e2"));
			dataParams.put("stlMoney", returnMap("888", "#6da0e2"));
			dataParams.put("stlExplain", returnMap("结算至1111111", "#6da0e2"));
			dataParams.put("stlTime", returnMap(sdf.format(new Date()), "#6da0e2"));
			dataParams.put("remark", returnMap("感谢您的使用", "#6da0e2"));
			sendParams.put("data", dataParams);
//			String doPost = httpRequestor.doPost(SEND_TEMPLATE_URL+"?access_token="+ACCESS_TOKEN, sendParams);
			String json = JsonUtil.toJson(sendParams);
			String doPost = HttpClientUtil.doPost(SEND_TEMPLATE_URL+"?access_token="+token, json);
			_log.info(doPost);
			result.put("wx", doPost);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}


	/**
	 * 参数组装
	 * @param value
	 * @param color
	 * @return
	 */
	private Map<String, String> returnMap(String value, String color){
		Map<String, String> map = new HashMap<String, String>();
		map.put("value", value);
		map.put("color", color);
		return map;
	}
}
